//
//  TTSearchViewController.m
//  TaoTuo
//
//  Created by admin on 2019/8/17.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTSearchViewController.h"
#import "LLSearchTextField.h"
#import "LLTagView.h"
#import "LLTagConfig.h"
#import "TTSearchInsertModel.h"
#import "TTGoodsListViewController.h"

@interface TTSearchViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIButton *deleteBtn;
@property (nonatomic, strong) LLSearchTextField *searchTF;
@property (nonatomic, strong) UILabel *hotLabel;
@property (nonatomic, strong) LLTagView *historyView;   // 搜索历史
@property (nonatomic, strong) LLTagView *hotView;   // 热门搜索

@property (nonatomic, strong) NSMutableArray *hotArray;    // 热门搜索内容

@end

@implementation TTSearchViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSArray *historyArray = [USER_DEFAULT objectForKey:historySearchContentKey];
    [self.historyView setupDatasArray:historyArray];
    
    [self.view setNeedsLayout];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.historyView resetView];
    [self.hotView resetView];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.hotLabel.top = self.historyView.bottom + 30;
        self.hotView.top = self.hotLabel.bottom;
        self.scrollView.contentSize = CGSizeMake(self.view.width, 200 + self.historyView.height + self.hotView.height);
    });
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = nil;
    UIButton *rightBtn = [UIButton createButtonWithTitle:@"取消" titleColor:UIColorHex(#333333) titleFont:[UIFont systemFontOfSize:14] backgroundColor:nil target:self action:@selector(clickRightBtn)];
    rightBtn.frame = CGRectMake(0, 0, 40, 44);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    _searchTF = [[LLSearchTextField alloc] initWithFrame:CGRectMake(0, 7, 500, 30)];
    _searchTF.backgroundColor = UIColorHex(F0F4F7);
    _searchTF.delegate = self;
    _searchTF.placeholder = @"输入 成品/系列/品牌 搜索";
    self.navigationItem.titleView = _searchTF;
    
    self.hotArray = [NSMutableArray array];
    /// 取出搜索热词
    NSString *path = [[NSBundle mainBundle] pathForResource:@"search_insert" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSError *error = nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    // 热门搜索词
    self.hotArray = [NSMutableArray array];
    for (NSDictionary *mDic in dic[@"hotSearch"]) {
        [self.hotArray addObject:[TTSearchInsertModel modelWithJSON:mDic]];
    }
    // 取出搜索词
    NSDictionary *hotDic = [USER_DEFAULT objectForKey:ad_data_key];
    NSArray *seararray = hotDic[@"SummaryList"];
    if (seararray) {
        [self.hotArray removeAllObjects];
        for (NSString *title in seararray) {
            TTSearchInsertModel *model = [[TTSearchInsertModel alloc] init];
            model.title = title;
            [self.hotArray addObject:model];
        }
    }
    
    
    [self setupSubviews];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self saveSearchHistoryWithText:textField.text];
    [self gotoSearchResultControlelrWithText:textField.text];
    
    return YES;
}

- (void)gotoSearchResultControlelrWithText:(NSString *)text
{
    NSDictionary *dic = @{
                          @"param.sourceType" : @(3),
                          @"param.searchKey" : text
                          };
    TTGoodsListViewController *goodsVC = [[TTGoodsListViewController alloc] initWithSearchName:text paramsDic:dic selectIndex:0];
    [self.navigationController pushViewController:goodsVC animated:YES];
}

// 点击搜索
- (void)clickRightBtn
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
// 点击删除
- (void)deleteBtnClick
{
    [self.historyView setupDatasArray:@[]];
    [USER_DEFAULT removeObjectForKey:historySearchContentKey];
    [USER_DEFAULT synchronize];
    
    [self.view setNeedsLayout];
}

// 保存搜索历史
- (void)saveSearchHistoryWithText:(NSString *)text
{
    if (text.length == 0) {
        return;
    }
    NSMutableArray *historyArray = [[USER_DEFAULT objectForKey:historySearchContentKey] mutableCopy];
    if (historyArray.count == 0) {
        historyArray = [NSMutableArray array];
    }
    self.searchTF.text = text;
    if ([historyArray containsObject:text]) {
        return;
    }
    [historyArray insertObject:text atIndex:0];
    [USER_DEFAULT setObject:historyArray forKey:historySearchContentKey];
    [USER_DEFAULT synchronize];
}


- (void)setupSubviews
{
    _scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_scrollView];
    
    UILabel *historyLabel = [UILabel labelWithTitle:@"历史搜索" color:UIColorHex(333333) font:[UIFont boldSystemFontOfSize:18]];
    historyLabel.frame = CGRectMake(10, 10, 120, 30);
    [self.scrollView addSubview:historyLabel];
    
    _deleteBtn = [UIButton createButtonWithImage:[UIImage imageNamed:@"lajitong"] target:self action:@selector(deleteBtnClick)];
    _deleteBtn.imageView.contentMode = UIViewContentModeCenter;
    _deleteBtn.frame = CGRectMake(self.view.width - 40, historyLabel.top, 40, 40);
    [self.scrollView addSubview:_deleteBtn];
    
    
    LLTagConfig *config = [[LLTagConfig alloc] init];
    config.minItemSpace = 10;
    config.minLineSpace = 10;
    config.sectionInset = UIEdgeInsetsZero;
    config.itemHeight = 28;
    config.tagNormalbackgroundColor = UIColorHex(#F5F5F5);
//    config.tagSelectbackgroundColor = kMainColor;
    config.cornerRadius = 14;
     
    // 历史搜索内容
    NSMutableArray *historyArray = [[USER_DEFAULT objectForKey:historySearchContentKey] mutableCopy];
    @weakify(self)
    _historyView = [[LLTagView alloc] initWithFrame:CGRectMake(0, historyLabel.bottom, self.view.width, 30) dataArray:historyArray selectItems:^(NSArray * _Nonnull selectArray) {
        @strongify(self)
        if (selectArray.count == 0) {
            return;
        }
        [self gotoSearchResultControlelrWithText:selectArray.firstObject];
        
    }];
    _historyView.canCancelSelect = YES;
    _historyView.backgroundColor = [UIColor whiteColor];
    _historyView.config = config;
    _historyView.allowMutiSelect = NO;
    [self.scrollView addSubview:_historyView];
    
    UILabel *hotLabel = [UILabel labelWithTitle:@"热门搜索" color:UIColorHex(333333) font:[UIFont boldSystemFontOfSize:18]];
    hotLabel.frame = CGRectMake(10, _historyView.bottom + 30, 120, 30);
    [self.scrollView addSubview:hotLabel];
    self.hotLabel = hotLabel;
    
    // 热门搜索内容
    NSMutableArray *hotArray = [NSMutableArray array];
    for (TTSearchInsertModel *model in self.hotArray) {
        [hotArray addObject:model.title];
    }

    _hotView = [[LLTagView alloc] initWithFrame:CGRectMake(0, hotLabel.bottom, self.view.width, 100) dataArray:hotArray selectItems:^(NSArray * _Nonnull selectArray) {
        @strongify(self)
        if (selectArray.count == 0) {
            return;
        }
        [self saveSearchHistoryWithText:selectArray.firstObject];
        [self gotoSearchResultControlelrWithText:selectArray.firstObject];
        
    }];
    
    _hotView.canCancelSelect = YES;
    _hotView.backgroundColor = [UIColor whiteColor];
    _hotView.config = config;
    _hotView.allowMutiSelect = NO;
    //    _hotView.layer.masksToBounds = YES;
    [self.scrollView addSubview:_hotView];
}


@end
